import json
from json import JSONDecodeError

import allure
import pytest
import requests

from common.readyaml import ReadYamlData
from common.recordlog import logs
from requests import utils


class SendRequests:
    """
    封装接口的请求
    """

    def send_request(self, **kwargs):

        session = requests.session()
        result = None
        cookie = {}
        try:
            result = session.request(**kwargs)
            set_cookie = requests.utils.dict_from_cookiejar(result.cookies)
            if set_cookie:
                cookie['Cookie'] = set_cookie
                ReadYamlData().write_yaml_data(cookie)
                logs.info("cookie：%s" % cookie)
            if result.text:
                try:
                    resp_json = json.loads(result.text)
                    pretty_resp = json.dumps(resp_json, ensure_ascii=False, indent=2)
                    logs.info(f"接口返回信息：\n{pretty_resp}")
                except JSONDecodeError:
                    logs.info(f"接口返回信息(非JSON)：{result.text}")
        except requests.exceptions.ConnectionError:
            logs.error("ConnectionError--连接异常")
            pytest.fail("接口请求异常，可能是request的连接数过多或请求速度过快导致程序报错！")
        except requests.exceptions.HTTPError:
            logs.error("HTTPError--http异常")
        except requests.exceptions.RequestException as e:
            logs.error(e)
            pytest.fail("请求异常，请检查系统或数据是否正常！")
        return result

    def run_main(self, name, url, case_name, header, method, cookies=None, file=None, **kwargs):
        """
        接口请求主函数
        :param url:
        :param data:
        :param header:
        :param method:
        :return:
        """
        try:
            # 收集报告日志信息
            logs.info(f'接口名称：{name}')
            logs.info(f'接口请求地址：{url}')
            logs.info(f'接口请求方法：{method}')
            logs.info(f'测试用例名称：{case_name}')
            logs.info(f'请求头：{header}')
            logs.info(f'Cookies：{cookies}')
            # 处理请求参数  json.dumps把字典转换为json格式
            #req_params = json.dumps(kwargs, ensure_ascii=False)
            req_params = json.dumps(kwargs, ensure_ascii=False, indent=2)
            if 'data' in kwargs.keys():
                logs.info(f'请求参数：\n{req_params}')
                allure.attach(req_params, f'请求参数', allure.attachment_type.TEXT)
            elif 'json' in kwargs.keys():
                logs.info(f'请求参数：\n{req_params}')
                allure.attach(req_params, f'请求参数', allure.attachment_type.TEXT)
            elif 'params' in kwargs.keys():
                logs.info(f'请求参数：\n{req_params}')
                allure.attach(req_params, f'请求参数', allure.attachment_type.TEXT)
            else:
                logs.info(f'请求参数：无')
        except Exception as e:
            logs.error(e)
        response = self.send_request(method=method,
                                     url=url,
                                     headers=header,
                                     cookies=cookies,
                                     verify=False,
                                     files=file,
                                     **kwargs)

        return response
